package com.cts.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * @projectName: CBlog
 * @package: com.cts.util
 * @className: RedisUtils
 * @author: chentongsheng
 * @description: TODO
 * @date: 2023/2/27 22:22
 * @version: 1.0
 */
@Component
@Slf4j
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 读取数据
     */

    public Object get(final String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 写入数据
     */
    public Boolean set(final String key, Object value) {
        if (StringUtils.isBlank(key)) {
            return false;
        }
        try {
            redisTemplate.opsForValue().set(key, value);
            log.info("存入redis成功，key：{}，value：{}", key, value);
            return true;
        } catch (Exception e) {
            log.error("存入redis失败，key：{}，value：{}", key, value);
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除数据
     */
    public Boolean remove(final String key) {
        if (StringUtils.isBlank(key)) {
            return false;
        }
        try {
            redisTemplate.delete(key);
            log.info("删除redis成功，key：{}", key);
            return true;
        } catch (Exception e) {
            log.error("删除redis失败，key：{}", key);
            e.printStackTrace();
        }
        return false;
    }
}
